package toOffer;

/**
 * @author YuanAo
 * @date 2025/1/3 16:20
 * @description 单词规律
 */

import java.util.LinkedHashMap;

/**
 * 给定一种规律 pattern 和一个字符串 s ，判断 s 是否遵循相同的规律。
 * <p>
 * 这里的 遵循 指完全匹配，例如， pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。
 * <p>
 * 示例1:
 * <p>
 * 输入: pattern = "abba", s = "dog cat cat dog"
 * 输出: true
 * 示例 2:
 * <p>
 * 输入:pattern = "abba", s = "dog cat cat fish"
 * 输出: false
 * 示例 3:
 * <p>
 * 输入: pattern = "aaaa", s = "dog cat cat dog"
 * 输出: false
 */
public class No290 {

    public static void main(String[] args) {
        String pattern = "abba", s = "dog cat cat dog";
        boolean flag = wordPattern(pattern, s);
        System.out.println(flag);
    }

    public static boolean wordPattern(String pattern, String s) {

        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        String[] patternS = pattern.split("");
        String[] sS = s.split(" ");
        for (int i = 0; i < patternS.length; i++) {
            map.put(patternS[i], sS[i]);
        }
        StringBuilder sb = new StringBuilder();
        for (String p : patternS) {
            sb.append(map.get(p));
        }
        String newS = sb.toString();
        String oldS = s.replaceAll(" ", "");
        return newS.equals(oldS);
    }
}
